package cn.itcast.utils;


import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
import java.util.ResourceBundle;

public class JdbcUtils {
    private JdbcUtils(){}

    private  static String driverClass;
    private  static String url;
    private  static String username;
    private  static String password;
    static {
        // 读取配置文件
//        InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("config.properties");
//        Properties prop = new Properties();
//        try {
//            prop.load(is);
//            driverClass = prop.getProperty("driverClass");
//            url = prop.getProperty("url");
//            username = prop.getProperty("name");
//            password = prop.getProperty("password");
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        try {
        ResourceBundle bundle = ResourceBundle.getBundle("config");
        driverClass = bundle.getString("driverClass");
        url = bundle.getString("url");
        username = bundle.getString("username");
        password = bundle.getString("password");

        Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取连接
    public static Connection getConnection(){
        try {
            Connection connection = DriverManager.getConnection(url,username,password);
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //释放资源
    public static void close(Connection con,Statement stat,ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //释放资源
    public static void close(Connection con,Statement stat) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
